package com.uam.web.common.utils;

import com.alibaba.fastjson.JSONArray;
import com.uam.web.common.vo.TrackPoint;

import java.util.*;
import java.util.stream.Collectors;

/**
 * List 传入数字，取出离这个数字最近的那一条记录下标值
 * @author Administrator
 */
public class ClosestNumber {

    public static void main(String[] args) {
        Random random = new Random();
        List<Long> numbers = new ArrayList<>();
       for(int i=0;i<20;i++){
           numbers.add(Long.valueOf(random.nextInt(20) + 1));
       }

        Collections.sort(numbers);
        for(int i=0;i<20;i++){
            System.out.println(i+"--"+numbers.get(i));
        }

        int randomNumber =random.nextInt(18) + 1 ;
        int closestNumber = findClosestNumber(numbers, randomNumber);
        System.out.println(randomNumber+"最接近的数字下标是：" + closestNumber);
    }



    public static int findClosestNumber(List<Long> numbers, long target) {
        Long closestNumber = numbers.get(0);
        Long minDistance = Math.abs(target - closestNumber);
        int index=0;
        for(int i=0;i<numbers.size();i++){
            Long number=numbers.get(i);
            Long distance = Math.abs(target - number);
            if (distance < minDistance) {
                minDistance = distance;
                index=i;
            }
        }
        return index;
    }

    public static int findIndexNumber(JSONArray numbers, long newTime) {

        long closestNumber = numbers.getObject(0, TrackPoint.class).getTime();
        long minDistance = newTime - closestNumber;
        if(minDistance<=0){
            minDistance=0;
        }

        int index=0;
        for(int i=0;i<numbers.size();i++){
            long number=  numbers.getObject(0,TrackPoint.class).getTime();
            long distance = newTime - number;
            if(distance <=0){
                continue;
            }
            if (distance < minDistance) {
                minDistance = distance;
                index=i;
            }
        }
        return index;
    }
}
